// 权限控制
import router from './router'
import store from './store'
import { asyncRoutes } from '@/router/asyncRoutes'

const WHITE_LIST = ['/login', '/404']

// 获取一级路由
function getFirstRoutePerms(perms) {
  const newArr = perms.map(item => {
    return item.split(':')[0]
  })
  return Array.from(new Set(newArr))
}

// 获取二级路由
function getSecondRoutePerms(perms) {
  const newArr = perms.map(item => {
    const arr = item.split(':')
    return `${arr[0]}:${arr[1]}`
  })
  return [...new Set(newArr)]
}

// 根据权限表识过滤路由表
function getRoutes(firstRoutePerms, secondRoutePerms, asyncRoutes) {
  // 过滤获取一级权限
  const firstRoutes = firstRoutePerms.includes('*') ? asyncRoutes
    : asyncRoutes.filter(item => firstRoutePerms.includes(item.permission))
  // 在一级路由下再过滤二级路由
  return firstRoutes.map(item => {
    return {
      ...item,
      children: secondRoutePerms.includes('*:*') ? item.children
        : item.children.filter(obj => secondRoutePerms.includes(obj.permission))
    }
  })
}

router.beforeEach(async(to, from, next) => {
  // 获取token
  const token = store.state.user.token
  // 如果有token，判断来源是否为登录页
  if (token) {
    if (to.path === '/login') {
      // 跳转到首页
      next('/')
    } else {
      next()
      const perms = await store.dispatch('menu/getProfile')
      const firstRoutePerms = getFirstRoutePerms(perms)
      console.log(firstRoutePerms)
      const secondRoutePerms = getSecondRoutePerms(perms)
      console.log(secondRoutePerms)
      const filterRoute = getRoutes(firstRoutePerms, secondRoutePerms, asyncRoutes)
      // console.log(asyncRoutes)
      // console.log('11111111111')
      // console.log(filterRoute)
      // 动态添加路由
      filterRoute.forEach(route => router.addRoute(route))
      // 过滤的了路由存在vuex,用于渲染菜单
      store.commit('menu/setMenuList', filterRoute)
    }
  } else {
    // 没有token，判断请求是否在白名单里
    if (WHITE_LIST.includes(to.path)) {
      next()
    } else {
      next('/login')
    }
  }
})
